﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Dt261.Base;
using Dt261.ble;
using Dt261.db;
using Dt261.help;
using Dt261.Model;
using Dt261.Views;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Panuon.UI.Silver;
using Windows.Devices.Bluetooth;

namespace Dt261.ViewModel
{
    class TestWindowViewModel : ViewModelBase
    {

        IniFile ini;
        private PureToneOptions option;
        private PureToneOptionsDb db;
        PureToneResultDb resultDB;
        MemberInfoDb memberDB;
        ResultDataSetDb datasetDB;
        ResultEntryDb entryDB;

        DisplayOptionDb displaydb;
        public DisPlayOption displayoption;

        string mac;

        private string playButtonText = "点击播放";
        private string talkButtonText = "点击通话";
        private bool needReset = true;
        private bool chOK= false;
        public bool needDisconnectTishi = false;

        private MemberInfo testMember;
        private Boolean mModeType;
        private Boolean isRightEar;
        private bool isMaskingOn;//掩蔽开启
        private bool isNormalOn;
        private bool isTracking;
        private bool isAutojump;//跳下一频率
        private bool isMaintainintensity;

        private int defaultStimulusIndex;
        private int stimulusStep;

        private string stimulusType;
        private string stimulusTime;
        private string maskingType;

        private bool istakling;
        private int toneDBValue;
        private int maskDBvalue;
        private int frequencyValue;

        private bool isRepsOn;

        private bool isRspEnable;

        public BleCore bluetooth;
        private string online = "OFF-LINE";
        private string onlineColor = "red";
        private string errMsg;
        private Boolean isReverseOn;
        private Boolean isTalkOn;
        private int slidervalue;

        public string viewID = "00";
        public bool needsend = false;

        public delegate void testModechanged(Dictionary<int, int> limitHz, Dictionary<int, TestItem> leftlist, Dictionary<int, TestItem> rightlist, bool isright);
        public delegate void testItemchanged(Dictionary<int, TestItem> list, bool isright,int mmtype = 0,int needLine = 0);
        //定义一个事件
        public event testItemchanged TestItemEvent;
        public event testModechanged TestModemEvent;
        ObservableCollection<int> mFrequencyNeed;
        ObservableCollection<int> mFrequencyAdd;
        public Dictionary<int, TestItem> leftResult = new Dictionary<int, TestItem>();
        public Dictionary<int, TestItem> rightResult = new Dictionary<int, TestItem>();
        public Dictionary<int, TestItem> leftBcResult = new Dictionary<int, TestItem>();
        public Dictionary<int, TestItem> rightBcResult = new Dictionary<int, TestItem>();

        PureToneResult toneresult;
        ResultDataSet lacdataset;
        ResultDataSet racdataset;
        ResultDataSet lbcdataset;
        ResultDataSet rbcdataset;
        ResultDataSet lffdataset;
        ResultDataSet rffdataset;

        public Dictionary<string, int> lastdbDictory = new Dictionary<string, int>();
        public Dictionary<string, int> lasthzDictory = new Dictionary<string, int>();

        Dictionary<int, int> limitHz = Config.limitHz;

        private string toneDbTextColor;
        private string maskDbTextColor;

        public TestWindowViewModel()
        {
            needReset = true;
            db = new PureToneOptionsDb(dbconfig.DatabaseFilename);
            option = db.GetOnePureToneOptionsByUserId(GlobalData.LoginUser.Uid);
            resultDB = new PureToneResultDb(dbconfig.DatabasePath);
            memberDB = new MemberInfoDb(dbconfig.DatabasePath);
            datasetDB = new ResultDataSetDb(dbconfig.DatabasePath);
            entryDB = new ResultEntryDb(dbconfig.DatabasePath);


            displaydb = new DisplayOptionDb(dbconfig.DatabasePath);
            displayoption = displaydb.GetOneDisPlayOptionByUserId(GlobalData.LoginUser.Uid);

            bluetooth = BleCore.shareInstance();
            //bluetooth.CurrentDevice.ConnectionStatusChanged += CurrentDevice_ConnectionStatusChanged;
            bluetooth.ValueChanged += eventRun;
            bluetooth.DeviceChanged += deviceRun;
            //bluetooth.StartBleDeviceWatcher();

            var basePath = Environment.CurrentDirectory;

            string cfgINI = System.IO.Path.Combine(basePath, "device.ini");
            IniFile ini = new IniFile(cfgINI);
            mac = ini.IniReadValue("Bind", "Device");

            try
            {
                if (!mac.IsNullOrEmpty())
                    bluetooth.SelectDeviceFromIdAsync(mac);
            }
            catch (Exception ex)
            {
               Notice.Show(ex.Message,"发生错误");
                

            }
            finally
            {
                
            }

            //Hz = "125";

            isAutojump = option.IsAutoJump;//自动跳频率

            DefaultStimulusIndex = 8;
            StimulusStep = option.StepValue;

     


        

       

            mFrequencyNeed = new ObservableCollection<int>();

            if (option.IsChecked125) { mFrequencyNeed.Add(125); }
            if (option.IsChecked250) { mFrequencyNeed.Add(250); }
            if (option.IsChecked500) { mFrequencyNeed.Add(500); }

            if (option.IsChecked750) { mFrequencyNeed.Add(750); }


            if (option.IsChecked1000) { mFrequencyNeed.Add(1000); }

            if (option.IsChecked1500) { mFrequencyNeed.Add(1500); }

            if (option.IsChecked2000) { mFrequencyNeed.Add(2000); }

            if (option.IsChecked3000) { mFrequencyNeed.Add(3000); }

            if (option.IsChecked4000) { mFrequencyNeed.Add(4000); }

            if (option.IsChecked6000) { mFrequencyNeed.Add(6000); }

            if (option.IsChecked8000) { mFrequencyNeed.Add(8000); }
            //    = new ObservableCollection<int>()
            //{ 125,250,500,1000,2000,4000,8000};


            Online = "OFF-LINE";
            Reset();






            mFrequencyAdd = new ObservableCollection<int>();
            //    = new ObservableCollection<int>()
            //{ 750,1500,3000,6000};


        }

        public void  Reset()
        {
            IsRightEar = true;
            MModeType = false;//20
            IsMaintainintensity = option.IsMaintain;//19
            if (option.IsMaintain == false)
                this.ToneDBValue = option.DefaultValue;//42
            else
                this.ToneDBValue = 30;
            this.MaskDBvalue = 30;
            this.FrequencyValue = 1000;
            this.slidervalue = 30;

           
            IsMaskingOn = false;//掩蔽开启
            IsNormalOn = false;
            IsTracking = false;//掩蔽音跟随测试音增减
            IsReverseOn = false;
            IsTalkOn = false;
            IsRspEnable = false;
            this.StimulusTimeSelect = this.StimulusTimeSource[0];
            this.MaskingTypeSelect = this.MaskingTypeSource[0];
            this.StimulusTypeSelect = this.StimulusTypeSource[0];
        }


        public void Dispose()
        {
            this.needDisconnectTishi = false;
            this.needReset = false;
            bluetooth.Dispose();
            bluetooth.ValueChanged -= eventRun;
            bluetooth.DeviceChanged -= deviceRun;
        }

        public int Slidervalue { get => slidervalue; set {
                slidervalue = value;
                RaisePropertyChanged();

                if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                   
                 
                    if(slidervalue >= 30 && slidervalue <=45)
                    {
                        ArrayList list = new ArrayList();
                        list.Add((this.slidervalue).ToString("X2"));
                        TLJCommand com = new TLJCommand(CommandType.CommandType_TalkToneAdd, CommandAction.CommandAction_Set, list);
                        byte[] dd = com.getProtocolHex();
                        bluetooth.Write(dd);

                        return;

                    }
                    else
                    {
                        ErrMsg = "通话增益值不支持该值";
                    }

           
                }
                else
                {
                    ErrMsg = "未连接设备";

                }
            }
        }
        public bool MModeType
        {
            get => mModeType; set
            {
                int lasttype = MModeType ? 1 : 0;
                mModeType = value;
                RaisePropertyChanged();

                this.MaskDBvalue = 30;
                this.limitHz = mModeType ? Config.limitGuDaoHz : Config.limitHz;

                if (TestModemEvent != null)
                {
                    TestModemEvent(this.limitHz, this.leftResult, this.rightResult, this.IsRightEar);
                }

                if (needsend != true)
                    return;

                if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    if (mModeType)
                    {
                        list.Add("01");
                    }
                    else
                    {
                        list.Add("00");
                    }

                    TLJCommand com = new TLJCommand(CommandType.CommandType_HeadPhoneTypeSelect, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";

                }

                int current = mModeType ? 1 : 0;
                if (lasttype != current)
                {
                    int leftorright = this.isRightEar ? 1 : 0;
                    lastdbDictory.Remove("DB" + lasttype + leftorright);
                    lastdbDictory.Add("DB" + lasttype + leftorright, this.ToneDBValue);
                    lasthzDictory.Remove("HZ" + lasttype + leftorright);
                    lasthzDictory.Add("HZ" + lasttype + leftorright, this.FrequencyValue);

                   
                    if (lastdbDictory.ContainsKey("DB" + current + leftorright))
                    {
                        this.ToneDBValue = lastdbDictory["DB" + current + leftorright];
                    }
                    else
                    {
                        this.ToneDBValue = option.IsMaintain ? 30 : option.DefaultValue;
                    }


                    if (lasthzDictory.ContainsKey("HZ" + current + leftorright))
                    {
                        this.FrequencyValue = lasthzDictory["HZ" + current + leftorright];
                    }
                    else
                    {
                        this.FrequencyValue = 1000;
                    }

                    //xgwen
                    //if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    //{
                    //    ArrayList list = new ArrayList();

                    //    list.Add((this.ToneDBValue + 10).ToString("X2"));


                    //    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneValue, CommandAction.CommandAction_Set, list);
                    //    byte[] dd = com.getProtocolHex();
                    //    bluetooth.Write(dd);
                    //}
                    //else
                    //{
                    //    ErrMsg = "未连接设备";
                    //}


                    //if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    //{
                    //    ArrayList list = new ArrayList();
                    //    //
                    //    Collection<int> hzs = new Collection<int> { 125, 250, 500, 1000, 1500, 2000, 3000, 4000, 6000, 8000 };
                    //    int index2 = hzs.IndexOf(this.FrequencyValue) + 1;

                    //    list.Add(index2.ToString("X2"));


                    //    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneSet, CommandAction.CommandAction_Set, list);
                    //    byte[] dd = com.getProtocolHex();
                    //    bluetooth.Write(dd);
                    //}
                    //else
                    //{
                    //    ErrMsg = "未连接设备";
                    //}

                    //xgwen
                }
 

            }
        }
        public bool IsRightEar
        {
            get => isRightEar; set
            {
                int lastleftorright = isRightEar ? 1 : 0;
                isRightEar = value; RaisePropertyChanged();

                if (this.IsRightEar)
                {

                    //List<TestItem> listChild = this.rightResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.rightResult = new ObservableCollection<TestItem>(listChild);
                    if (TestItemEvent != null) TestItemEvent(this.rightResult, true);
                }
                else
                {

                    //List<TestItem> listChild = this.leftResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.leftResult = new ObservableCollection<TestItem>(listChild);
                    //// DMSkin.Core.Broadcast.PushBroadcast<string>("testItemChange");
                    ///TestItemEvent
                    if (TestItemEvent != null)
                        TestItemEvent(this.leftResult, false);
                }

                if (needsend != true)
                    return;

                if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    if (isRightEar)
                    {
                        list.Add("01");
                    }
                    else
                    {
                        list.Add("00");
                    }

                    TLJCommand com = new TLJCommand(CommandType.CommandType_EarSelect, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";

                }
                int current = isRightEar ? 1 : 0;

                if(current != lastleftorright)
                {
                    int mtype = this.MModeType ? 1 : 0;
                    lastdbDictory.Remove("DB" + mtype + lastleftorright);
                    lastdbDictory.Add("DB" + mtype + lastleftorright, this.ToneDBValue);
                    lasthzDictory.Remove("HZ" + mtype + lastleftorright);
                    lasthzDictory.Add("HZ" + mtype + lastleftorright, this.FrequencyValue);


           
                    if (lastdbDictory.ContainsKey("DB" + mtype + current))
                    {
                        this.ToneDBValue = lastdbDictory["DB" + mtype + current];
                    }
                    else
                    {
                        this.ToneDBValue = option.IsMaintain ? 30: option.DefaultValue;
                    }


                    if (lasthzDictory.ContainsKey("HZ" + mtype + current))
                    {
                        this.FrequencyValue = lasthzDictory["HZ" + mtype + current];
                    }
                    else
                    {
                        this.FrequencyValue = 1000;
                    }


                    //if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    //{
                    //    ArrayList list = new ArrayList();

                    //    list.Add((this.ToneDBValue + 10).ToString("X2"));


                    //    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneValue, CommandAction.CommandAction_Set, list);
                    //    byte[] dd = com.getProtocolHex();
                    //    bluetooth.Write(dd);
                    //}
                    //else
                    //{
                    //    ErrMsg = "未连接设备";
                    //}


                    //if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    //{
                    //    ArrayList list = new ArrayList();
                    //    //
                    //    Collection<int> hzs = new Collection<int> { 125, 250, 500, 1000, 1500, 2000, 3000, 4000, 6000, 8000 };
                    //    int index2 = hzs.IndexOf(this.FrequencyValue) + 1;

                    //    list.Add(index2.ToString("X2"));


                    //    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneSet, CommandAction.CommandAction_Set, list);
                    //    byte[] dd = com.getProtocolHex();
                    //    bluetooth.Write(dd);
                    //}
                    //else
                    //{
                    //    ErrMsg = "未连接设备";
                    //}
                }
              
            }
        }
        public bool IsMaskingOn
        {
            get => isMaskingOn; set
            {
                isMaskingOn = value; RaisePropertyChanged();

                if (TestItemEvent != null)
                    TestItemEvent(this.IsRightEar ? this.rightResult : this.leftResult, this.IsRightEar);
                if (needsend != true)
                    return;
                if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    if (isMaskingOn)
                    {
                        list.Add("01");
                    }
                    else
                    {
                        list.Add("00");
                    }

                    TLJCommand com = new TLJCommand(CommandType.CommandType_MaskingTone, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";

                }
            }
        }
        public bool IsNormalOn
        {
            get => isNormalOn; set
            {
                isNormalOn = value; RaisePropertyChanged();

                if (needsend != true)
                    return;
                //if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {

                    if (isNormalOn)
                    {
                        this.startPlay();

                    }
                    else
                    {
                        this.stopPlay();
                    }

                }
                //else
                //{
                //    ErrMsg = "未连接设备";

                //}
            }
        }

        public string PlayButtonText { get => playButtonText; set { playButtonText = value; RaisePropertyChanged(); } }
        public string TalkButtonText { get => talkButtonText; set { talkButtonText = value; RaisePropertyChanged(); } }
        public bool IsTracking { get => isTracking; set { isTracking = value; RaisePropertyChanged(); } }
        public bool IsMaintainintensity
        {
            get => isMaintainintensity; set
            {
                isMaintainintensity = value; RaisePropertyChanged();

 

            }
        }

        public bool IsAutojump { get => isAutojump; set { isAutojump = value; RaisePropertyChanged(); } }

        public string ToneDbTextColor { get => toneDbTextColor; set { toneDbTextColor = value; RaisePropertyChanged(); } }
        public string MaskDbTextColor { get => maskDbTextColor; set { maskDbTextColor = value; RaisePropertyChanged(); } }
        public int DefaultStimulusIndex { get => defaultStimulusIndex; set { defaultStimulusIndex = value; RaisePropertyChanged(); } }
        public int StimulusStep { get => stimulusStep; set { stimulusStep = value; RaisePropertyChanged(); } }
        public string StimulusType { get => stimulusType; set { stimulusType = value; RaisePropertyChanged(); } }
        public string StimulusTime { get => stimulusTime; set { stimulusTime = value; RaisePropertyChanged(); } }
        public string MaskingType { get => maskingType; set { maskingType = value; RaisePropertyChanged(); } }
        public bool Istakling { get => istakling; set { istakling = value; RaisePropertyChanged(); } }
        public int ToneDBValue
        {
            get => toneDBValue; set
            {
                toneDBValue = value; RaisePropertyChanged();

                if (toneDBValue >= 100)
                    ToneDbTextColor = "Red";
                else
                    ToneDbTextColor = "White";

                if (this.IsRightEar)
                {

                    //List<TestItem> listChild = this.rightResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.rightResult = new ObservableCollection<TestItem>(listChild);
                    if (TestItemEvent != null) TestItemEvent(this.rightResult, true);
                }
                else
                {

                    //List<TestItem> listChild = this.leftResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.leftResult = new ObservableCollection<TestItem>(listChild);
                    //// DMSkin.Core.Broadcast.PushBroadcast<string>("testItemChange");
                    ///TestItemEvent
                    if (TestItemEvent != null)
                        TestItemEvent(this.leftResult, false);
                }

                //if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                //{
                //    ArrayList list = new ArrayList();

                //    list.Add((this.toneDBValue + 10).ToString("X2"));


                //    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneValue, CommandAction.CommandAction_Set, list);
                //    byte[] dd = com.getProtocolHex();
                //    bluetooth.Write(dd);
                //}
                //else
                //{
                //    ErrMsg = "未连接设备";
                //}

            }
        }
        public int MaskDBvalue { get => maskDBvalue; set {
                maskDBvalue = value;
                if (maskDBvalue >= 100)
                    MaskDbTextColor = "Red";
                else
                    MaskDbTextColor = "White";
                RaisePropertyChanged();
                if (TestItemEvent != null)
                    TestItemEvent(this.IsRightEar ? this.rightResult : this.leftResult, this.IsRightEar);
            } }
        public int FrequencyValue { get => frequencyValue; set {
                frequencyValue = value;
                RaisePropertyChanged();

                if(MModeType == false)
                {
                    if (this.IsRightEar)
                    {

                        //List<TestItem> listChild = this.rightResult.ToList();
                        //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                        ////List列表转为ObservableCollection集合
                        //this.rightResult = new ObservableCollection<TestItem>(listChild);
                        if (TestItemEvent != null) TestItemEvent(this.rightResult, true);
                    }
                    else
                    {

                        //List<TestItem> listChild = this.leftResult.ToList();
                        //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                        ////List列表转为ObservableCollection集合
                        //this.leftResult = new ObservableCollection<TestItem>(listChild);
                        //// DMSkin.Core.Broadcast.PushBroadcast<string>("testItemChange");
                        if (TestItemEvent != null) TestItemEvent(this.leftResult, false);
                    }
                }
                else
                {
                    if (this.IsRightEar)
                    {

          
                        if (TestItemEvent != null) TestItemEvent(this.rightBcResult, true,1, displayoption.IsLinkBc?1:0);
                    }
                    else
                    {

                        if (TestItemEvent != null) TestItemEvent(this.leftBcResult, false,1, displayoption.IsLinkBc ? 1 : 0);
                    }
                }

            } }
        public bool IsRepsOn { get => isRepsOn; set { isRepsOn = value; RaisePropertyChanged(); } }
        public string ErrMsg { get => errMsg; set { errMsg = value; RaisePropertyChanged(); } }
        public bool IsRspEnable { get => isRspEnable; set { isRspEnable = value; RaisePropertyChanged(); } }

        public bool IsReverseOn
        {
            get => isReverseOn; set
            {
                isReverseOn = value; RaisePropertyChanged();
                if (needsend != true)
                    return;
                if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    if (isRepsOn)
                    {
                        list.Add("01");
                    }
                    else
                    {
                        list.Add("00");
                    }

                    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneReverse, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";

                }
            }
        }
        public bool IsTalkOn
        {
            get => isTalkOn; set
            {
                isTalkOn = value; RaisePropertyChanged();
                TalkClick(IsTalkOn);
            }
        }

        public void TalkClick(bool istalk)
        {
            ArrayList list = new ArrayList();
            if (istalk == false)
            {
                list.Add("00");
                TalkButtonText = "点击通话";
            }
            else
            {
                list.Add("01");
                TalkButtonText = "松开停止";

            }
            if (needsend != true)
                return;
            if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
    

                TLJCommand com = new TLJCommand(CommandType.CommandType_TestTalkBack, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";

            }
        }


        public MemberInfo TestMember { get => testMember; set => testMember = value; }

        public string Online
        {
            get => online; set { online = value; RaisePropertyChanged(); }
        }

        public string OnlineColor
        {
            get => onlineColor; set { onlineColor = value; RaisePropertyChanged(); }
        }

        private RelayCommand playCommand;

        public RelayCommand PlayCommand
        {
            get
            {
                if (playCommand == null)
                {
                    playCommand = new RelayCommand(() => startPlay());
                }
                return playCommand;
            }

        }
        public void startPlay()
        {
            ArrayList list = new ArrayList();
            list.Add("01");
            if (isNormalOn)
            {

                PlayButtonText = "播放中";
            }
            else
            {

                PlayButtonText = "播放中";
            }

            if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
     

                TLJCommand com = new TLJCommand(CommandType.CommandType_TestStartAndStop, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";

            }
        }

        public void stopPlay()
        {
            ArrayList list = new ArrayList();
            //if (isNormalOn)
            //{
            //    list.Add("01");
            //}
            //else
            {
                list.Add("00");
            }

            if (isNormalOn)
            {

                PlayButtonText = "暂停中";
            }
            else
            {

                PlayButtonText = "点击播放";
            }
            if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
      

                TLJCommand com = new TLJCommand(CommandType.CommandType_TestStartAndStop, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";

            }
        }


        private RelayCommand turnMaskingCommand;

        public RelayCommand TurnMaskingCommand
        {
            get
            {
                if (turnMaskingCommand == null)
                {
                    turnMaskingCommand = new RelayCommand(() => turnMasking());
                }
                return turnMaskingCommand;
            }
        }

        public void turnMasking()
        {
            this.IsMaskingOn = !this.IsMaskingOn;

            if (TestItemEvent != null)
                TestItemEvent(this.IsRightEar ? this.rightResult : this.leftResult, this.IsRightEar);

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();
                if (isMaskingOn)
                {
                    list.Add("01");
                }
                else
                {
                    list.Add("00");
                }

                TLJCommand com = new TLJCommand(CommandType.CommandType_MaskingTone, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";

            }
            //MaskingTone_Close

        }



        private RelayCommand turnTrackingOnCommand;

        public RelayCommand TurnTrackingOnCommand
        {
            get
            {
                if (turnTrackingOnCommand == null)
                {
                    turnTrackingOnCommand = new RelayCommand(() => turnTrackingOn());
                }
                return turnTrackingOnCommand;
            }
        }



        public void turnTrackingOn()
        {
            this.IsTracking = !this.IsTracking;

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                //ArrayList list = new ArrayList();
                //if (isMaskingOn)
                //{
                //    list.Add("01");
                //}
                //else
                //{
                //    list.Add("00");
                //}

                //TLJCommand com = new TLJCommand(CommandType.CommandType_TestStartAndStop, CommandAction.CommandAction_Set, list);
                //byte[] dd = com.getProtocolHex();
                //bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }


        private RelayCommand turnNormalOnCommand;

        public RelayCommand TurnNormalOnCommand
        {
            get
            {
                if (turnNormalOnCommand == null)
                {
                    turnNormalOnCommand = new RelayCommand(() => turnNormalOn());
                }
                return turnNormalOnCommand;
            }
        }



        public void turnNormalOn()
        {
            this.IsNormalOn = !this.IsNormalOn;

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();
                if (isMaskingOn)
                {
                    list.Add("01");
                }
                else
                {
                    list.Add("00");
                }

                TLJCommand com = new TLJCommand(CommandType.CommandType_TestStartAndStop, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }

        private RelayCommand turnLeftOrRightCommand;

        public RelayCommand TurnLeftOrRightCommand
        {
            get
            {
                if (turnLeftOrRightCommand == null)
                {
                    turnLeftOrRightCommand = new RelayCommand(() => changeToLeftOrRight());
                }
                return turnLeftOrRightCommand;
            }
        }



        public void changeToLeft(bool left)
        {
            this.IsRightEar = !left;

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();
                if (IsRightEar)
                {
                    list.Add("01");
                }
                else
                {
                    list.Add("00");
                }

                TLJCommand com = new TLJCommand(CommandType.CommandType_EarSelect, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }

        public void changeToLeftOrRight()
        {
            this.IsRightEar = !this.IsRightEar;

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();
                if (IsRightEar)
                {
                    list.Add("01");
                }
                else
                {
                    list.Add("00");
                }

                TLJCommand com = new TLJCommand(CommandType.CommandType_EarSelect, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }


        private RelayCommand<string> saveCommand;

        public RelayCommand<string> SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new RelayCommand<string>((noreps) => saveItem(noreps));
                }
                return saveCommand;
            }
        }



        public void saveItem(string noreps)
        {
            //this.IsRightEar 
            TestItem item = new TestItem();
            item.Hz = this.FrequencyValue;
            item.Db = this.ToneDBValue;
            if (Boolean.Parse(noreps))
                item.IsUserResp = false;
            else
                item.IsUserResp = true;



            if (this.IsMaskingOn)
            {
                item.Mask = true;
                item.MaskV = MaskDBvalue;
                //...
                
            }
            else
            {
                item.Mask = false;
                item.MaskV = 0;
                //...
            }

      

        

            if(this.MModeType == true)
            {
                if (this.IsRightEar)
                {
                    if (!this.isMaskingOn)
                    {
                        item.MarkType = displayoption.BcRightType;
                    }
                    else
                    {
                        item.MarkType = displayoption.BcRightMaskedType;
                    }
                    if (this.rightBcResult.ContainsKey(item.Hz))
                    {
                        this.rightBcResult.Remove(item.Hz);
                    }
                    this.rightBcResult.Add(item.Hz, item);

                    //List<TestItem> listChild = this.rightResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.rightResult = new ObservableCollection<TestItem>(listChild);
                    TestItemEvent(this.rightBcResult, true,1,displayoption.IsLinkBc?1:0);
                }
                else
                {
                    if (!this.isMaskingOn)
                    {
                        item.MarkType = displayoption.BcLeftType;
                    }
                    else
                    {
                        item.MarkType = displayoption.BcLeftMaskedType;
                    }

                    if (this.leftBcResult.ContainsKey(item.Hz))
                    {
                        this.leftBcResult.Remove(item.Hz);
                    }
                    this.leftBcResult.Add(item.Hz, item);
                    //List<TestItem> listChild = this.leftResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.leftResult = new ObservableCollection<TestItem>(listChild);
                    //// DMSkin.Core.Broadcast.PushBroadcast<string>("testItemChange");
                    TestItemEvent(this.leftBcResult, false,1,displayoption.IsLinkBc ? 1 : 0);
                }
            }
            else
            {
                if (this.IsRightEar)
                {
                    if(this.isMaskingOn)
                    {
                        item.MarkType = displayoption.AcRightMaskedType;
                    }
                    else
                    {
                        item.MarkType = displayoption.AcRightType;
                    }
                   
                       



                    if (this.rightResult.ContainsKey(item.Hz))
                    {
                        this.rightResult.Remove(item.Hz);
                    }
                    this.rightResult.Add(item.Hz, item);

                    //List<TestItem> listChild = this.rightResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.rightResult = new ObservableCollection<TestItem>(listChild);
                    TestItemEvent(this.rightResult, true);
                }
                else
                {
                    if (this.isMaskingOn)
                    {
                        item.MarkType = displayoption.AcLeftMaskedType;
                    }
                    else
                    {
                        item.MarkType = displayoption.AcLeftType;
                    }
                    if (this.leftResult.ContainsKey(item.Hz))
                    {
                        this.leftResult.Remove(item.Hz);
                    }
                    this.leftResult.Add(item.Hz, item);
                    //List<TestItem> listChild = this.leftResult.ToList();
                    //listChild.Sort(delegate (TestItem p1, TestItem p2) { return Comparer<int>.Default.Compare(p1.Hz, p2.Hz); });
                    ////List列表转为ObservableCollection集合
                    //this.leftResult = new ObservableCollection<TestItem>(listChild);
                    //// DMSkin.Core.Broadcast.PushBroadcast<string>("testItemChange");
                    TestItemEvent(this.leftResult, false);
                }
            }
          

            if (isAutojump)
            {
                upFrequency();
            }
        }


        private RelayCommand<string> savetTestResultCommand;

        public RelayCommand<string> SaveTestResultCommand
        {
            get
            {
                if (savetTestResultCommand == null)
                {
                    savetTestResultCommand = new RelayCommand<string>((noreps) => saveTestResult(noreps));
                }
                return savetTestResultCommand;
            }
        }



        public void saveTestResult(string noreps)
        {
            //this.IsRightEar 
            //            {
            //                NSLog(@"right:%@ \n left:%@", self.rightResult, self.leftResult);

            this.TestMember.LastTestTime = DateTime.Now;

            memberDB.UpdateMember(this.TestMember);

            PureToneResult result = this.Toneresult;
            result.DataSets = new List<ResultDataSet>();
            result.MemberId = this.TestMember.Uid;
            result.IsUpload = 0;
            result.TestType = this.MModeType == false ? 0 : 1;
            result.Uid = System.Guid.NewGuid().ToString("N");

            if (bluetooth!= null && bluetooth.CurrentDeviceMAC != null)
            {
                result.DevicesModel = "DT261";
                result.DeviceWT = bluetooth.CurrentDeviceMAC;
            }


            result.Name = this.TestMember.Name;
            result.Gender = TestMember.Gender;
            result.Birthday = TestMember.Birthday;

            result.HospitalId = TestMember.HospitalId;

            result.State = displayoption.IsLinkBc?1:0;


            //result.DeviceWT = TestMember.DeviceWT;
            result.Tinnitus = TestMember.Tinnitus;
            result.Strength = TestMember.Strength;
            result.DeafAidLeftModel = TestMember.DeafAidLeftModel;
            result.DeafAidRightModel = TestMember.DeafAidRightModel;
            result.DeafAidThreshold = TestMember.DeafAidThreshold;
            result.DeafAidRoutine = TestMember.DeafAidRoutine;
            result.DeafAidVolume = TestMember.DeafAidVolume;
            result.Mark = TestMember.Mark;
            result.ListenWord = TestMember.ListenWord;
            result.SoundField= TestMember.SoundField;

         

            result.AcLeftType = displayoption.AcLeftType;
            result.AcLeftMaskedType= displayoption.AcLeftMaskedType;
            result.AcRightType= displayoption.AcRightType;
            result.AcRightMaskedType= displayoption.AcRightMaskedType;
            result.BcLeftType= displayoption.BcLeftType;
            result.BcLeftMaskedType= displayoption.BcLeftMaskedType;
            result.BcRightType= displayoption.BcRightType;
            result.BcRightMaskedType= displayoption.BcRightMaskedType;
      


            resultDB.AddPureToneResult(result);

            ArrayList testRecord = new ArrayList();

            {
                ResultDataSet ldataset = this.Lbcdataset;

                datasetDB.UpdateResultDataSet(ldataset);

                foreach (int key in this.leftBcResult.Keys)
                {
                    //            NSDictionary* valueDict = @{@"hz":@(self.frequencyValue),@"db":@(self.toneDBValue),@"mask":@(self.isMaskingOn),@"maskV":@(self.maskDBValue)};
                    ResultEntry entry = new ResultEntry();
                    TestItem value = this.leftBcResult[key];
                    entry.ValueX = value.Hz;
                    entry.ValueY = value.Db;
                    entry.PointState = value.Mask ? 1 : 0;
                    entry.PointType = value.MaskV;
                    entry.Mmtype = 1;
                    entry.Uid = System.Guid.NewGuid().ToString("N");

                    entry.IsUserResp = value.IsUserResp ? 1 : 0;
                    entry.YanbiType = value.MaskType;
                    entry.MarkType = value.MarkType;//value[@"markType"];
                    entry.TestToneTime = value.TestToneTime;// value[@"testToneTime"];
                    entry.TestToneType = value.TestToneType;//value[@"testToneType"];
                    entry.DataSetId = ldataset.Uid;

                    entry.MarkType = value.MarkType;

                    entryDB.UpdateResultEntry(entry);
                    ldataset.Entrys.Add(entry);



                }
                result.DataSets.Add(ldataset);
                testRecord.Add(ldataset.getResultDictory());
            }

            {
                ResultDataSet rdataset = this.Rbcdataset;

                rdataset.IsRight = 1;
                rdataset.ResultId = result.Uid;
                rdataset.Uid = System.Guid.NewGuid().ToString("N");

                int datasetId = datasetDB.UpdateResultDataSet(rdataset);

                foreach (int key in this.rightBcResult.Keys)
                {
                    //            NSDictionary* valueDict = @{@"hz":@(self.frequencyValue),@"db":@(self.toneDBValue),@"mask":@(self.isMaskingOn),@"maskV":@(self.maskDBValue)};
                    ResultEntry entry = new ResultEntry();
                    TestItem value = this.rightBcResult[key];
                    entry.ValueX = value.Hz;
                    entry.ValueY = value.Db;
                    entry.PointState = value.Mask ? 1 : 0;
                    entry.PointType = value.MaskV;
                    entry.Mmtype = 1;

                    entry.Uid = System.Guid.NewGuid().ToString("N");
                    entry.IsUserResp = value.IsUserResp ? 1 : 0;
                    entry.YanbiType = value.MaskType;
                    entry.MarkType = value.MarkType;//value[@"markType"];
                    entry.TestToneTime = value.TestToneTime;// value[@"testToneTime"];
                    entry.TestToneType = value.TestToneType;//value[@"testToneType"];
                    entry.DataSetId = rdataset.Uid;

                    entry.MarkType = value.MarkType;
                    entryDB.AddResultEntry(entry);

                    rdataset.Entrys.Add(entry);

                }
                result.DataSets.Add(rdataset);
                testRecord.Add(rdataset.getResultDictory());
            }


                {
                    ResultDataSet ldataset = this.Lacdataset;

                    datasetDB.UpdateResultDataSet(ldataset);

                    foreach (int key in this.leftResult.Keys)
                    {
                        //            NSDictionary* valueDict = @{@"hz":@(self.frequencyValue),@"db":@(self.toneDBValue),@"mask":@(self.isMaskingOn),@"maskV":@(self.maskDBValue)};
                        ResultEntry entry = new ResultEntry();
                        TestItem value = this.leftResult[key];
                        entry.ValueX = value.Hz;
                        entry.ValueY = value.Db;
                        entry.PointState = value.Mask ? 1 : 0;
                        entry.PointType = value.MaskV;
                        entry.Mmtype = 0;
                        entry.Uid = System.Guid.NewGuid().ToString("N");

                        entry.IsUserResp = value.IsUserResp ? 1 : 0;
                        entry.YanbiType = value.MaskType;
                        entry.MarkType = value.MarkType;//value[@"markType"];
                        entry.TestToneTime = value.TestToneTime;// value[@"testToneTime"];
                        entry.TestToneType = value.TestToneType;//value[@"testToneType"];
                        entry.DataSetId = ldataset.Uid;

                        entry.MarkType = value.MarkType;
                    entryDB.UpdateResultEntry(entry);
                    ldataset.Entrys.Add(entry);
                }
                result.DataSets.Add(ldataset);
                testRecord.Add(ldataset.getResultDictory());
            }


                    {
                        ResultDataSet rdataset = this.Racdataset;

                        rdataset.IsRight = 1;
                        rdataset.ResultId = result.Uid;
                        rdataset.Uid = System.Guid.NewGuid().ToString("N");

                        int datasetId = datasetDB.UpdateResultDataSet(rdataset);

                        foreach (int key in this.rightResult.Keys)
                        {
                            //            NSDictionary* valueDict = @{@"hz":@(self.frequencyValue),@"db":@(self.toneDBValue),@"mask":@(self.isMaskingOn),@"maskV":@(self.maskDBValue)};
                            ResultEntry entry = new ResultEntry();
                            TestItem value = this.rightResult[key];
                            entry.ValueX = value.Hz;
                            entry.ValueY = value.Db;
                            entry.PointState = value.Mask ? 1 : 0;
                            entry.PointType = value.MaskV;
                            entry.Mmtype = 0;

                            entry.Uid = System.Guid.NewGuid().ToString("N");
                            entry.IsUserResp = value.IsUserResp ? 1 : 0;
                            entry.YanbiType = value.MaskType;
                            entry.MarkType = value.MarkType;//value[@"markType"];
                            entry.TestToneTime = value.TestToneTime;// value[@"testToneTime"];
                            entry.TestToneType = value.TestToneType;//value[@"testToneType"];
                            entry.DataSetId = rdataset.Uid;

                    entry.MarkType = value.MarkType;

                    entryDB.AddResultEntry(entry);
                    rdataset.Entrys.Add(entry);
                }
            
                testRecord.Add(rdataset.getResultDictory());
            }


            //上传接口http


            if (Http.PostHost != null && Http.PostHost != "")
            {
 


                //image = gh.getBitmapByPureToneResult(result, 0);

                //image = gh.getBitmapByPureToneResult(result, 1);


                var http = Http.SharedHttp();

              


                Dictionary<string, Object> dict = new Dictionary<string, Object>();

                dict.Add("id",result.Uid);
                dict.Add("mac", mac);
                dict.Add("status", 0);
                dict.Add("equipmentType", 0);
                dict.Add("memberId", testMember.Uid);

                //    //    var time = startTime.AddSeconds(Convert.ToDouble(info.birthday) / 1000);
                //    //    m.Birthday = time;
                //    //    m.Age = Convert.ToInt32((DateTime.Now.Year - time.Year));

                dict.Add("age", DateTime.Now.Year- testMember.Birthday.Year);
                dict.Add("noiseVal", 0);
                long jan1st1970ms = new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime().Ticks;//, DateTimeKind.Local
                dict.Add("birthday", (testMember.Birthday.Ticks - jan1st1970ms) / 10000);
                dict.Add("modifyDate",  (System.DateTime.UtcNow.ToUniversalTime().Ticks - 621355968000000000) / 10000);
                dict.Add("createDate", (System.DateTime.Now.Ticks - jan1st1970ms) / 10000);
                dict.Add("testRecord", testRecord);
                //得改造一下m
                //NSDictionary* dict = @{
                //    @"equipmentType":@0,
                //                   @"id":result.id,
                //                   @"mac":@"",
                //                   //@"birthday":@((long long)([member.birthday timeIntervalSince1970])*1000),
                //                   @"memberId":result.member.id,
                //                   @"noiseVal":@0,
                //                   @"modifyDate":result.modifyDate,
                //                   @"status":result.state,
                //                   @"testRecord":testRecords,
                //                   };
                //Dictionary<string, Object>[] array = new Dictionary<string, Object>[1];
                //array[0] = dict;

                StringContent jsonContent = new StringContent(JsonConvert.SerializeObject(dict), Encoding.UTF8, "application/json");

                MultipartFormDataContent content = new MultipartFormDataContent();

                content.Add(jsonContent, "info");

                if(GlobalData.ImageType == 1)
                {
                    resultDB.GetChildrenByUid(result);
                    DrawHearingImage gh = new DrawHearingImage();
                    Bitmap image = gh.getBitmapByPureToneResult(result, 2);
            



                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                    byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以，至于区别么，下面有解释


                    content.Add(new ByteArrayContent(bytes), "picture", "double.png");
                    ms.Close();
                }
                else if (GlobalData.ImageType == 2)
                {
                    resultDB.GetChildrenByUid(result);
                    DrawHearingImage gh = new DrawHearingImage();
                    Bitmap image = gh.getBitmapByPureToneResult(result, 0);//左耳图
                    Bitmap image2 = gh.getBitmapByPureToneResult(result, 1);//you耳图


                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                    byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以，至于区别么，下面有解释

                    MemoryStream ms2 = new MemoryStream();
                    image2.Save(ms2, System.Drawing.Imaging.ImageFormat.Bmp);
                    byte[] bytes2 = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以，至于区别么，下面有解释


                    content.Add(new ByteArrayContent(bytes), "picture", "left.png");
                    content.Add(new ByteArrayContent(bytes2), "picture", "right.png");



                    ms2.Close();
                    ms.Close();
                }


#if DEBUG1
                string res = http.GetJSonResponse(JsonConvert.SerializeObject(array), Http.PostHost + "tlyht/formal/tlj/uploadAudiometer", "post");
#else
                string res = http.GetMultipartResponse(content, Http.PostHost + "tlyht/formal/tlj/uploadAudiometerOpen", "post");
# endif


                if (res != null)
                {
                    Console.WriteLine(res);

                    JObject o = (JObject)JsonConvert.DeserializeObject(res);

                    if (null == Http.errorWithJsonObject(o))
                    {
                        Notice.Show("听力测试结果发送.", "提示", 3, MessageBoxIcon.Success);
                    }
                        //    IList<MemberNetInfo> listOrder = new List<MemberNetInfo>();


                        //    listOrder = JsonConvert.DeserializeObject<IList<MemberNetInfo>>(o["Persons"].ToString());

                        //    if (listOrder.Count <= 0)

                        //    {
                        //        // Log4.WriteLog("没有获取到可以写入的数据记录");
                        //        return;
                        //    }
                        //    //for (int i = 0; i < listOrder.Count(); i++)
                        //    //{

                        //    //    //循环解析每一个实体
                        //    //    MemberNetInfo info = listOrder[i];

                        //    //    MemberInfo m = db.GetOneMemberByUid(info.id);

                        //    //    if (m == null)
                        //    //        m = new MemberInfo();

                        //    //    m.Uid = info.id;
                        //    //    m.UserId = info.ordinaryUserId;
                        //    //    m.Name = info.name;
                        //    //    m.Phone = info.phone;
                        //    //    m.Note = info.relationship;
                        //    //    m.Mark = info.remarks;
                        //    //    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                        //    //    var time = startTime.AddSeconds(Convert.ToDouble(info.birthday) / 1000);
                        //    //    m.Birthday = time;
                        //    //    m.Age = Convert.ToInt32((DateTime.Now.Year - time.Year));
                        //    //    //Convert.ToInt32(info.age);
                        //    //    m.Gender = info.sex.Equals("0") ? 1 : 0;
                        //    //    //m.IdCard = IdCard;
                        //    //    //m.Insurance = Insurance;
                        //    //    m.Address = info.address;
                        //    //    m.ZipCode = info.zipcode;
                        //    //    //m.AllergyHistory = AllergyHistory;
                        //    //    //m.History = History;
                        //    //    //m.DeafAidRoutine = DeafAidRoutine;
                        //    //    //m.DeafAidThreshold = DeafAidThreshold;
                        //    //    //m.SoundField = SoundField;
                        //    //    //m.Tinnitus = Tinnitus;
                        //    //    //m.Strength = Strength;
                        //    //    //m.DeafAidLeftModel = DeafAidLeftModel;
                        //    //    //m.DeafAidRightModel = DeafAidRightModel;
                        //    //    //m.DeviceWT = DeviceWT;
                        //    //    //m.Note = Chengxu;
                        //    //    //m.DeafAidVolume = DeafAidVolume;
                        //    //    //m.IdCard = IdCard;
                        //    //    db.UpdateMember(m);

                        //    //}

                        //}
                        //else
                        //{
                        //    //this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                        //}


                    }



            }



            Notice.Show("听力测试结果已保存.", "提示", 3, MessageBoxIcon.Success);
                DMSkin.Core.Broadcast.PushBroadcast("NavigationBack2", "TestWindowViewModel");

                DMSkin.Core.Broadcast.PushBroadcast("CLOSEWINDOW", "TestWindowViewModel"); //("CLOSEWINDOW", (obj) =>
            }
        


        private RelayCommand deleteCommand;

        public RelayCommand DeleteCommand
        {
            get
            {
                if (deleteCommand == null)
                {
                    deleteCommand = new RelayCommand(() => deleteItem());
                }
                return deleteCommand;
            }
        }



        public void deleteItem()
        {

            if(MModeType == true)
            {
                if (this.IsRightEar)
                {
                    this.rightBcResult.Remove(this.FrequencyValue);
                    TestItemEvent(this.rightBcResult, true,1);
                }
                else

                {
                    this.leftBcResult.Remove(this.FrequencyValue);

                    TestItemEvent(this.leftBcResult, false,1);
                }
            }
            //this.IsRightEar
            else
            {
                if (this.IsRightEar)
                {
                    this.rightResult.Remove(this.FrequencyValue);
                    TestItemEvent(this.rightResult, true);
                }
                else

                {
                    this.leftResult.Remove(this.FrequencyValue);

                    TestItemEvent(this.leftResult, false);
                }
            }
   
        }

        private RelayCommand upMaskingCommand;

        public RelayCommand UpMaskingsCommand
        {
            get
            {
                if (upMaskingCommand == null)
                {
                    upMaskingCommand = new RelayCommand(() => upMasking());
                }
                return upMaskingCommand;
            }
        }


        public void upMasking()
        {
            this.MaskDBvalue += this.StimulusStep;



            if (this.MaskDBvalue > this.limitHz[this.FrequencyValue])
            {
                this.MaskDBvalue = this.limitHz[this.FrequencyValue];
            }

            //缺少越界检查

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();

                list.Add((this.MaskDBvalue + 10).ToString("X2"));


                TLJCommand com = new TLJCommand(CommandType.CommandType_MaskingToneValue, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }

        private RelayCommand downMaskingCommand;

        public RelayCommand DownMaskingCommand
        {
            get
            {
                if (downMaskingCommand == null)
                {
                    downMaskingCommand = new RelayCommand(() => downMasking());
                }
                return downMaskingCommand;
            }
        }


        public void downMasking()
        {
            this.MaskDBvalue -= this.StimulusStep;

            //缺少越界检查
            if (this.MaskDBvalue < -10)
            {
                this.MaskDBvalue = -10;
            }

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();

                list.Add((this.MaskDBvalue + 10).ToString("X2"));


                TLJCommand com = new TLJCommand(CommandType.CommandType_MaskingToneValue, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }

        private RelayCommand upStimulusCommand;

        public RelayCommand UpStimulusCommand
        {
            get
            {
                if (upStimulusCommand == null)
                {
                    upStimulusCommand = new RelayCommand(() => upStimulus());
                }
                return upStimulusCommand;
            }
        }


        public void upStimulus()
        {
            this.ToneDBValue += this.StimulusStep;

            //缺少越界检查
            if (this.ToneDBValue >= this.limitHz[this.FrequencyValue])
            {
                this.ToneDBValue = this.limitHz[this.FrequencyValue];
                this.IsRspEnable = true;
            }
            else
            {
                this.IsRspEnable = false;
            }

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();

                list.Add((this.ToneDBValue + 10).ToString("X2"));


                TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneValue, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }

            if(IsTracking)
            {
                upMasking();
            }

        }

        private RelayCommand downStimulusCommand;

        public RelayCommand DownStimulusCommand
        {
            get
            {
                if (downStimulusCommand == null)
                {
                    downStimulusCommand = new RelayCommand(() => downStimulus());
                }
                return downStimulusCommand;
            }
        }


        public void downStimulus()
        {
            this.ToneDBValue -= this.StimulusStep;

            //缺少越界检查

            if (this.ToneDBValue < -10)
            {
                this.ToneDBValue = -10;
            }
            if (this.ToneDBValue >= this.limitHz[this.FrequencyValue])
            {

                this.IsRspEnable = true;
            }
            else
            {
                this.IsRspEnable = false;
            }

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();

                list.Add((this.ToneDBValue + 10).ToString("X2"));


                TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneValue, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }

            if (IsTracking)
            {
                downMasking();
            }

        }


        private RelayCommand upFrequencyCommand;

        public RelayCommand UpFrequencyCommand
        {
            get
            {
                if (upFrequencyCommand == null)
                {
                    upFrequencyCommand = new RelayCommand(() => upFrequency());
                }
                return upFrequencyCommand;
            }
        }


        public void upFrequency()
        {
            int index = this.mFrequencyNeed.IndexOf(this.FrequencyValue);
            if (index != this.mFrequencyNeed.Count() - 1)
                this.FrequencyValue = this.mFrequencyNeed[index + 1];
            else
                this.FrequencyValue = this.mFrequencyNeed[0];

            if (this.isMaintainintensity)
            {
                if (limitHz[this.FrequencyValue] == -10)
                {
                    upFrequency();
                    return;
                }
                if (this.ToneDBValue > limitHz[this.FrequencyValue])
                {
                    this.ToneDBValue = limitHz[this.FrequencyValue];
                }
            }
            else
            {
                if (limitHz[this.FrequencyValue] == -10)
                {
                    upFrequency();
                    return;
                }
                this.ToneDBValue = option.DefaultValue;
            }

            //缺少越界检查

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();
                //
                Collection<int> hzs = new Collection<int> { 125, 250, 500,750, 1000, 1500, 2000, 3000, 4000, 6000, 8000 };
                int index2 = hzs.IndexOf(this.FrequencyValue) + 1;

                list.Add(index2.ToString("X2"));


                TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneSet, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }

        private RelayCommand downFrequencyCommand;

        public RelayCommand DownFrequencyCommand
        {
            get
            {
                if (downFrequencyCommand == null)
                {
                    downFrequencyCommand = new RelayCommand(() => downFrequency());
                }
                return downFrequencyCommand;
            }
        }


        public void downFrequency()
        {
            int index = this.mFrequencyNeed.IndexOf(this.FrequencyValue);
            if (index != 0)
                this.FrequencyValue = this.mFrequencyNeed[index - 1];
            else
            {
                this.FrequencyValue = this.mFrequencyNeed.LastOrDefault();
            }

            if (this.isMaintainintensity)
            {
                if (limitHz[this.FrequencyValue] == -10)
                {
                    downFrequency();
                    return;
                }
                if (this.ToneDBValue > limitHz[this.FrequencyValue])
                {
                    this.ToneDBValue = limitHz[this.FrequencyValue];
                }
            }
            else
            {
                if (limitHz[this.FrequencyValue] == -10)
                {
                    downFrequency();
                    return;
                }
                this.ToneDBValue = option.DefaultValue;
            }
            //缺少越界检查

            if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                ArrayList list = new ArrayList();

                Collection<int> hzs = new Collection<int> { 125, 250, 500,750, 1000, 1500, 2000, 3000, 4000, 6000, 8000 };
                int index2 = hzs.IndexOf(this.FrequencyValue) + 1;

                list.Add(index2.ToString("X2"));


                TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneSet, CommandAction.CommandAction_Set, list);
                byte[] dd = com.getProtocolHex();
                bluetooth.Write(dd);
            }
            else
            {
                ErrMsg = "未连接设备";
            }


        }


        private MaskingType maskingTypeSelect;
        public MaskingType MaskingTypeSelect
        {
            get
            {
                return this.maskingTypeSelect;
            }
            set
            {
                this.maskingTypeSelect = value;

                RaisePropertyChanged();

                if (needsend != true)
                    return;
                if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    list.Add(this.maskingTypeSelect.Code);
                    TLJCommand com = new TLJCommand(CommandType.CommandType_MaskingToneTypeSelect, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";
                }
            }
        }

        private ObservableCollection<MaskingType> _maskingTypeS = null;

        public ObservableCollection<MaskingType> MaskingTypeSource
        {
            get
            {
                if (this._maskingTypeS == null)
                {
                    this._maskingTypeS = new ObservableCollection<MaskingType>() {
                       // new MaskingType() { Index = 0, Code = "00", Name = "白噪音" },
                        new MaskingType() {  Index = 1, Code = "01", Name = "窄带噪声"  }

                 };


                }
                return this._maskingTypeS;
            }
            set
            {
                this._maskingTypeS = value;
                RaisePropertyChanged();
            }
        }


        private StimulusType stimulusTypeSelect;
        public StimulusType StimulusTypeSelect
        {
            get
            {
                return this.stimulusTypeSelect;
            }
            set
            {
                this.stimulusTypeSelect = value;

                RaisePropertyChanged();

                if (needsend != true)
                    return;
                if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    list.Add(this.stimulusTypeSelect.Code);
                    TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneType, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";
                }

                this.ToneDBValue =  option.IsMaintain ? 30 : option.DefaultValue;
                this.MaskDBvalue = 30;
                this.FrequencyValue = 1000;

            }
        }

        private ObservableCollection<StimulusType> _stimulusTypeS = null;

        public ObservableCollection<StimulusType> StimulusTypeSource
        {
            get
            {
                if (this._stimulusTypeS == null)
                {
                    this._stimulusTypeS = new ObservableCollection<StimulusType>() {
                        new StimulusType() { Index = 0, Code = "01", Name = "纯音" },
                        new StimulusType() {  Index = 1, Code = "02", Name = "啭音"  }

                 };


                }
                return this._stimulusTypeS;
            }
            set
            {
                this._stimulusTypeS = value;
                RaisePropertyChanged();
            }
        }


        private StimulusTime stimulusTimeSelect;
        public StimulusTime StimulusTimeSelect
        {
            get
            {
                return this.stimulusTimeSelect;
            }
            set
            {
                this.stimulusTimeSelect = value;

                RaisePropertyChanged();

                if (needsend != true)
                    return;
                if (bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {
                    ArrayList list = new ArrayList();
                    list.Add(this.stimulusTimeSelect.Code);
                    TLJCommand com = new TLJCommand(CommandType.CommandType_TestTonePlayTime, CommandAction.CommandAction_Set, list);
                    byte[] dd = com.getProtocolHex();
                    bluetooth.Write(dd);
                }
                else
                {
                    ErrMsg = "未连接设备";
                }
            }
        }

        private ObservableCollection<StimulusTime> _stimulusTimeS = null;

        public ObservableCollection<StimulusTime> StimulusTimeSource
        {
            get
            {
                if (this._stimulusTimeS == null)
                {
                    this._stimulusTimeS = new ObservableCollection<StimulusTime>() {
                        new StimulusTime() { Index = 0, Code = "00", Name = "连续" },
                        new StimulusTime() { Index = 1, Code = "01", Name = "0.5秒" },
                        new StimulusTime() { Index = 2, Code = "02", Name = "1秒" },
                        new StimulusTime() {  Index = 3, Code = "04", Name = "2秒"  }
                        //@[@"连续",@"0.5秒",@"1秒",@"2秒"];
                 };


                }
                return this._stimulusTimeS;
            }
            set
            {
                this._stimulusTimeS = value;
                RaisePropertyChanged();
            }
        }

        public PureToneResult Toneresult
        {
            get
            {
                if (toneresult == null)
                {
                    toneresult = new PureToneResult();

                    toneresult.MemberId = this.TestMember.Uid;
                    toneresult.IsUpload = 0;
                    toneresult.TestType = this.MModeType == false ? 0 : 1;
                    toneresult.Uid = System.Guid.NewGuid().ToString("N");
                }

                return toneresult;
            }
        }

            

        public ResultDataSet Lacdataset {
            get
            {
                if (lacdataset == null)
                {
                    lacdataset = new ResultDataSet();
                    lacdataset.IsRight = 0;
                    lacdataset.ResultId = Toneresult.Uid;
                    lacdataset.Uid = System.Guid.NewGuid().ToString("N");
                }

                return lacdataset;
            }
         }
        public ResultDataSet Racdataset
        {
            get
            {
                if (racdataset == null)
                {
                    racdataset = new ResultDataSet();
                    racdataset.IsRight = 1;
                    racdataset.ResultId = Toneresult.Uid;
                    racdataset.Uid = System.Guid.NewGuid().ToString("N");
                }

                return racdataset;
            }
            set => racdataset = value;
        }
        public ResultDataSet Lbcdataset {
            get
            {
                if (lbcdataset == null)
                {
                    lbcdataset = new ResultDataSet();
                    lbcdataset.IsRight = 0;
                    lbcdataset.HeadsetMode = 1;
                    lbcdataset.ResultId = Toneresult.Uid;
                    lbcdataset.Uid = System.Guid.NewGuid().ToString("N");
                }

                return lbcdataset;
            }
            set => lbcdataset = value; }
        public ResultDataSet Rbcdataset
        {
            get
            {
                if (rbcdataset == null)
                {
                    rbcdataset = new ResultDataSet();
                    rbcdataset.IsRight = 1;
                    rbcdataset.HeadsetMode = 1;
                    rbcdataset.ResultId = Toneresult.Uid;
                    rbcdataset.Uid = System.Guid.NewGuid().ToString("N");
                }

                return rbcdataset;
            }
            set => rbcdataset = value; }
        public ResultDataSet Lffdataset
        {
            get
            {
                if (lffdataset == null)
                {
                    lffdataset = new ResultDataSet();
                    lffdataset.IsRight = 0;
                    lffdataset.ResultId = Toneresult.Uid;
                    lffdataset.Uid = System.Guid.NewGuid().ToString("N");
                }

                return lffdataset;
            }
            set => lffdataset = value; }
        public ResultDataSet Rffdataset
        {
            get
            {
                if (rffdataset == null)
                {
                    rffdataset = new ResultDataSet();
                    rffdataset.IsRight = 1;
                    rffdataset.ResultId = Toneresult.Uid;
                    rffdataset.Uid = System.Guid.NewGuid().ToString("N");
                }

                return rffdataset;
            }
            set => rffdataset = value; }

  

        private IniFile logIni()
        {
          
                if(ini == null)
            {
                var basePath = Environment.CurrentDirectory;

                string cfgINI = System.IO.Path.Combine(basePath, "log.ini");
                ini = new IniFile(cfgINI);
                ini.IniWriteValue("开始", "Log", DateTime.Now.ToString());
            }
   
            return ini;
        }

        public void initData()
        {
            Console.WriteLine(" initData + needReset=" + needReset + "chOK" + chOK);
            if (needReset == true && chOK == true && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                 Reset();
                {

                    TLJCommand com = new TLJCommand(CommandAction.CommandAction_Set);

                    {//20
                        CommandInfo inf = new CommandInfo(CommandType.CommandType_ViewSectct, viewID);
                        com.appendWithCommandInfo(inf);
                    }
                    {//42
                        this.ToneDBValue = option.IsMaintain ? 30 : option.DefaultValue;//42
                        CommandInfo inf = new CommandInfo(CommandType.CommandType_TestToneValue, (this.toneDBValue + 10).ToString("X2"));
                        com.appendWithCommandInfo(inf);
                    }
                    {//19
                        IsMaintainintensity = option.IsMaintain;//19
                        CommandInfo inf = new CommandInfo(CommandType.CommandType_KeepDB, IsMaintainintensity ? "01" : "00");
                        com.appendWithCommandInfo(inf);

                    }





                    if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    {
                        byte[] dd = com.getProtocolHex();
                        bluetooth.Write(dd);
                    }
                    else
                    {
                        Console.WriteLine("bluetooth.CurrentDevice.ConnectionStatus：" + bluetooth.CurrentDevice.ConnectionStatus);
                    }

                }
#if OLD

                    //20
                    if (bluetooth != null && bluetooth.CurrentDevice != null && bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                    {
                        ArrayList list = new ArrayList();              
                        {
                            list.Add(viewID);//00纯音测听 01 言语测听 02 纯音手动校准 03 纯音自动校准
                        }

                        TLJCommand com = new TLJCommand(CommandType.CommandType_ViewSectct, CommandAction.CommandAction_Set, list);
                        byte[] dd = com.getProtocolHex();
                        bluetooth.Write(dd);
                    }
                    this.ToneDBValue = option.IsMaintain?30:option.DefaultValue;//42
                    {
                        ArrayList list = new ArrayList();

                        list.Add((this.toneDBValue + 10).ToString("X2"));


                        TLJCommand com = new TLJCommand(CommandType.CommandType_TestToneValue, CommandAction.CommandAction_Set, list);
                        byte[] dd = com.getProtocolHex();
                        bluetooth.Write(dd);
                    }

                    IsMaintainintensity = option.IsMaintain;//19
#endif
                needReset = false;

                needsend = true;
            }
       
        }
        public void eventRun(MsgType type, string str, byte[] data = null)
        {


            if (type == MsgType.BLEData)
            {
                var s = TLJConvert.byteToHexStr(data);
#if DEBUG
                Console.WriteLine("RECV：" + s);
                logIni().IniWriteValue("Msg",  DateTime.Now.ToString(), s);
                ErrMsg = "收到数据" + s;
#else
                ErrMsg = "最后响应时间："+ DateTime.Now.ToString();
#endif
                TLJCommand c = new TLJCommand();
                c.parseWithHexData(data);
            }
            else if(type == MsgType.ChOK)
            {
#if DEBUG
                logIni().IniWriteValue("Msg", DateTime.Now.ToString(), "ChOK");
#endif
                chOK = true;

                //this.bluetooth.Connect();
                initData();




            }
            else if(type == MsgType.BLEStatus)
            {
                if (this.bluetooth.CurrentDevice != null && this.bluetooth.CurrentDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
                {

                    Online = "ON-LINE";
                    OnlineColor = "green";
                    needDisconnectTishi = true;
                    initData();
                }
                else
                {

                    needReset = true;
                    chOK = false;
                    needsend = false;
                    Online = "OFF-LINE";
                    OnlineColor = "red";

                    if (needDisconnectTishi)
                    {
                        needDisconnectTishi = false;
                       
                        ThreadPool.QueueUserWorkItem(delegate
                        {
                            SynchronizationContext.SetSynchronizationContext(new
                                DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                            SynchronizationContext.Current.Post(pl =>
                            {
                                var result = MessageBoxX.Show("连接设备已断开,是否重新连接？", "提醒", null, MessageBoxButton.YesNo, new Panuon.UI.Silver.Core.MessageBoxXConfigurations()
                                {
                                    MessageBoxStyle = MessageBoxStyle.Modern,
                                    MessageBoxIcon = MessageBoxIcon.Warning,
                                    ButtonBrush = "#F1C825".ToColor().ToBrush(),
                                });
                                // MessageBoxResult result = MessageBox.Show("连接设备已断开", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {


                                    bluetooth.SelectDeviceFromIdAsync(mac);

                                }

                                //vm.doResponseOK(dataBuffer);
                            }, null);
                        });


                    }

                }

                ErrMsg = str;
#if DEBUG
                Console.WriteLine(data);
                Console.WriteLine(str);
                

                logIni().IniWriteValue("Msg", DateTime.Now.ToString(), str);
#endif
            }
            else
            {
                ErrMsg = str;
#if DEBUG
                Console.WriteLine(data);
                Console.WriteLine(str);


                logIni().IniWriteValue("Msg", DateTime.Now.ToString(), str);
#endif
            }



        }



        public void deviceRun(MsgType type, string str, string Id)
        {

            //ThreadPool.QueueUserWorkItem(delegate
            //{
            //    SynchronizationContext.SetSynchronizationContext(new
            //        DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
            //    SynchronizationContext.Current.Post(pl =>
            //    {                    //里面写真正的业务内容
            //        KnownDevices.Add(new Device() { ID = "蓝牙地址：" + Id.Substring(Id.LastIndexOf("-") + 1), Name = str != null ? str : "未知" });
            //    }, null);
            //});

#if DEBUG
            Console.WriteLine(str + ":" + Id);

#endif
        }

        public void doResponseOK(Byte[] data)
        {

            TLJCommand com = new TLJCommand(CommandAction.CommandAction_Reply);

            ArrayList list = new ArrayList();
            CommandInfo.parseWithHexData(data, list);

            foreach (CommandInfo s in list)
            {
                com.appendWithCommandInfo(s);
            }

            byte[] dd = com.getProtocolHex();
            bluetooth.Write(dd);
        }
    } 
}
